Ext.BLANK_IMAGE_URL = "../script/ext-2.0.2/resources/images/default/s.gif";

// var roleStore = new Ext.data.Store({
//    proxy: new Ext.data.HttpProxy({url: 'userInfo!getRole.action?dateTime='+new Date().getTime()}),
//    reader: new Ext.data.JsonReader({
//        root: 'param',
//        fields:["key","value"]
//    }),
//    remoteSort: true
// });
//
// roleStore.load();

// var roleSelect = new Ext.form.ComboBox({
// 					  id:'roleCodeValue',
// 					  name:'roleCodeValue',
// 					  fieldLabel: '角色',
// 				      hiddenName: 'roleCode',
// 				      store: roleStore,
// 				      valueField:'key',
// 			          displayField:'value',
// 			          typeAhead: true,
// 			          mode: 'local',
// 			          triggerAction: 'all',
// 			          resizable:true,
// 			          emptyText:'请选择角色...',
// 			          allowBlank:false,
// 			          anchor:'95%',
// 			          forceSelection:true
// 					});
//
// var orgTreeLoader = new Ext.tree.TreeLoader({dataUrl:'../util/orgTree!getAllTree.action?dateTime='+new Date().getTime()});
//
// var orgTree = new Ext.ux.ComboBoxTree({
// 		name:'orgId1',
// 		hiddenName:'orgId1',
// 		fieldLabel: '机构',
// 		resizable:true,
// 		width :200,
// 		height:300,
// 		tree : {
// 			xtype:'treepanel',
// 			loader: orgTreeLoader,
//        	 	root : new Ext.tree.AsyncTreeNode({id:'0',draggable:false,text:'机构树'})
//     	},
//     	emptyText:'请选择机构...',
// 		selectNodeModel:'exceptRoot'
// 	});
//
// var orgTreeTemp = new Ext.ux.ComboBoxTree({
// 		name:'userOrg',
// 		hiddenName:'userOrg',
// 		fieldLabel: '机构',
// 		resizable:true,
// 		anchor:'95%',
// 		tree : {
// 			xtype:'treepanel',
// 			loader: orgTreeLoader,
//        	 	root : new Ext.tree.AsyncTreeNode({id:'0',draggable:false,text:'机构树'})
//     	},
//     	emptyText:'请选择机构...',
// 		selectNodeModel:'exceptRoot',
// 		allowBlank:false
// 	});

var classNameTemp = new Ext.form.TextField({
    id: 'classNameTemp',
    name: 'userNameTemp',
    width: 100
});

var storeClassManage = new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
        url: 'children/class!list.action?dateTime=' + new Date().getTime()
    }),
    reader: new Ext.data.JsonReader({
        root: 'ZANY',
        totalProperty: "results",
        fields: ["name", "createTime", "creater","id"]
    }),
    sortInfo: {field: 'harmDate', direction: 'DESC'},// 排序信息
    remoteSort: true
});

storeClassManage.load();

var sm = new Ext.grid.CheckboxSelectionModel();

var colClassManage = new Ext.grid.ColumnModel([sm,
    {header: "班级名称", dataIndex: "name", width: 10, sortable: true},
    {header: "创建时间", dataIndex: "createTime", width: 10, sortable: true,renderer:function (val) {
            if(val==''){
                return ''
            }
            return new Date(val).format("Y-m-d H:i:s");
    }},
    {header: "创建人", dataIndex: "creater", width: 10, sortable: true},
    {header: "ID", dataIndex: "id", width: 10, sortable: true ,hidden:true}
]);

var oneTbar = new Ext.Toolbar({
    items: ['-', {text: '&nbsp;&nbsp;查&nbsp;&nbsp;询&nbsp;&nbsp;', iconCls: 'yes', handler: getList},
        '-', {text: '新增班级', iconCls: 'add', handler: insertinfo},
        '-', {text: '&nbsp;&nbsp;删&nbsp;&nbsp;除&nbsp;&nbsp;', iconCls: 'remove', handler: delinfo}
    ]
});

var classManage = new Ext.grid.GridPanel({
    id: 'classManage',
    title: '[班级管理]信息维护',
    height: 500,
    stripeRows: true,
    bodyStyle: 'width:100%',
    disableSelection: true,
    cm: colClassManage,
    viewConfig: {
        forceFit: true
    },
    store: storeClassManage,
    iconCls: 'details',
    animCollapse: true,
    trackMouseOver: false,
    loadMask: {msg: '正在加载[用户管理]信息，请稍侯……'},
    selModel: sm,
    tbar: ['-', new Ext.form.Label({text: '班级名称:'}), '-', classNameTemp],
    listeners: {
        'render': function () {
            oneTbar.render(this.tbar); //add one tbar
        }
    },
    bbar: new Ext.PagingToolbar({
        pageSize: 20,
        store: storeClassManage,
        displayInfo: true,
        emptyMsg: '没有记录'
    })
});

function update() {
    if (Ext.getCmp("classManage").getSelectionModel().hasSelection()) {
        Ext.MessageBox.confirm('Message', '请问您真的要重置密码？', function (btn) {
            if (btn == 'yes') {
                var ids = new Array();
                var records = Ext.getCmp("classManage").getSelectionModel().getSelections();
                for (var i = 0, len = records.length; i < len; i++) {
                    ids[i] = records[i].data["userCode"];
                }
                Ext.Ajax.request({
                    url: 'userInfo!update.action?dateTime=' + new Date().getTime(),
                    params: {updateId: ids},
                    success: function (response, options) {
                        var response = Ext.util.JSON.decode(response.responseText);
                        if (response.success) {
                            ZANY.util.Msg('信息', "重置密码成功！");
                        } else if (!response.success) {
                            ZANY.util.Msg('信息', "重置密码失败，如有问题请联系系统管理员！");
                        }
                    }
                });
            }
        })
    } else {
        ZANY.util.Msg('提示信息', "请选择用户后再操作！");
    }
}

function delinfo() {
    if (Ext.getCmp("classManage").getSelectionModel().hasSelection()) {
        Ext.MessageBox.confirm('Message', '请问您真的要删除所选数据么？', function (btn) {
            if (btn == 'yes') {
                var ids = new Array();
                var records = Ext.getCmp("classManage").getSelectionModel().getSelections();
                for (var i = 0, len = records.length; i < len; i++) {
                    ids[i] = records[i].data["id"];
                }
                console.log(ids);
                Ext.Ajax.request({
                    url: 'children/class!delete.action?dateTime=' + new Date().getTime(),
                    params: {delId: ids},
                    success: function (response, options) {
                        var response = Ext.util.JSON.decode(response.responseText);
                        if (response.success) {
                            Ext.getCmp('classManage').getStore().reload(); //刷新Grid
                            ZANY.util.Msg('信息', "删除角色信息成功！");
                        } else if (!response.success) {
                            ZANY.util.Msg('信息', "删除角色信息失败，如有问题请联系系统管理员！");
                        }
                    }
                });
            }
        })
    } else {
        ZANY.util.Msg('提示信息', "请选择用户后再操作！");
    }
}

var fp = new Ext.FormPanel({
    id: 'ext_form',
    labelWidth: 100,
    waitMsg: '正在提交，请稍后...',
    frame: true,
    bodyStyle: 'padding:5px 5px 0',
    width: 400,
    reader: new Ext.data.JsonReader({
        root: 'ZANY',
        totalProperty: "results",
        fields: ["name"]
    }),
    items: [{
        layout: 'column',
        layout: 'form',
        defaultType: 'textfield',
        items: [{
            fieldLabel: '班级名称',
            name: 'name',
            id: 'name',
            maxLength: 10,
            anchor: '95%',
            allowBlank: false
        },new Ext.form.Hidden({name:'id'}),
        ]
    }]
});

var winKey = new Ext.Window({
    id: "ext_win",
    title: '[新增班级]',
    width: 400,
    closeAction: 'hide',
    modal: true,
    iconCls: 'add',
    buttons: [{
        text: '提交',
        handler: function () {
            // alert(fp.getForm().findField("name").getValue())
            // alert(fp.getForm().findField("id").getValue())
            // console.log(this)
            // return;
            var id =  fp.getForm().findField("id").getValue()
            var url = id=='' ? "children/class!save.action" :"children/class!update.action"

            if (fp.form.isValid()) {
                fp.form.submit({
                    url: url,
                    waitTitle: "新增用户",
                    waitMsg: '正在提交数据,请稍后... ...',
                    success: function () {
                        Ext.getCmp('classManage').getStore().reload(); //刷新Grid
                        fp.form.reset();
                        storeClassManage.modified = [];//将修改过的记录置为空，如果不清空，则修改过的数据会一直保留
                        Ext.MessageBox.alert('提示信息', '维护用户成功！');
                        winKey.hide();
                    },
                    failure: function (form, action) {
                        Ext.MessageBox.alert('提示信息', '维护用户失败,请联系系统管理员!' + action.result.msg);
                    }
                });
            } else {
                ZANY.util.Msg('添加提示', '数据不完整！');
            }
        }
    }, {
        text: '取消', handler: function () {
            winKey.hide();
            fp.form.reset();
        }
    }],
    items: [fp]
});

function insertinfo() {
    winKey.show();
    // orgTreeTemp.setValue('');
    // roleSelect.setValue('');
    // fp.getForm().findField("userName").getEl().dom.readOnly = false;
    // fp.getForm().findField("userCode").getEl().dom.readOnly = false;
}

classManage.addListener('rowdblclick', function (e) {
        if (Ext.getCmp("classManage").getSelectionModel().hasSelection()) {
            getDetail();
        }
    }, classManage
);

function getDetail() {
    var records = Ext.getCmp("classManage").getSelectionModel().getSelected();
    var id = records.data["id"];
    var name = records.data["name"]
    // fp.getForm().load({
    //     url: 'children/class!detail.action?dateTime=' + new Date().getTime() + '&id='+id,
    //     waitMsg: 'Loading'
    // });
    winKey.show();
    fp.getForm().findField("name").setValue(name);
    fp.getForm().findField("id").setValue(id);
}

function updateNO() {
    if (Ext.getCmp("classManage").getSelectionModel().hasSelection()) {
        Ext.MessageBox.confirm('Message', '请问您真的要禁止使用么？', function (btn) {
            if (btn == 'yes') {
                var ids = new Array();
                var records = Ext.getCmp("classManage").getSelectionModel().getSelections();
                for (var i = 0, len = records.length; i < len; i++) {
                    ids[i] = records[i].data["userCode"];
                }
                Ext.Ajax.request({
                    url: 'userInfo!updateSts.action?dateTime=' + new Date().getTime() + '&sts=0',
                    params: {updateId: ids},
                    success: function (response, options) {
                        var response = Ext.util.JSON.decode(response.responseText);
                        if (response.success) {
                            Ext.getCmp('classManage').getStore().reload(); //刷新Grid
                            ZANY.util.Msg('信息', "禁止使用成功！");
                        } else if (!response.success) {
                            ZANY.util.Msg('信息', "禁止使用失败，如有问题请联系系统管理员！");
                        }
                    }
                });
            }
        })
    } else {
        ZANY.util.Msg('提示信息', "请选择用户后再操作！");
    }
}

function updateYES() {
    if (Ext.getCmp("classManage").getSelectionModel().hasSelection()) {
        Ext.MessageBox.confirm('Message', '请问您真的要恢复使用么？', function (btn) {
            if (btn == 'yes') {
                var ids = new Array();
                var records = Ext.getCmp("classManage").getSelectionModel().getSelections();
                for (var i = 0, len = records.length; i < len; i++) {
                    ids[i] = records[i].data["userCode"];
                }
                Ext.Ajax.request({
                    url: 'userInfo!updateSts.action?dateTime=' + new Date().getTime() + '&sts=1',
                    params: {updateId: ids},
                    success: function (response, options) {
                        var response = Ext.util.JSON.decode(response.responseText);
                        if (response.success) {
                            Ext.getCmp('classManage').getStore().reload(); //刷新Grid
                            ZANY.util.Msg('信息', "恢复使用成功！");
                        } else if (!response.success) {
                            ZANY.util.Msg('信息', "恢复使用失败，如有问题请联系系统管理员！");
                        }
                    }
                });
            }
        })
    } else {
        ZANY.util.Msg('提示信息', "请选择用户后再操作！");
    }
}

function resetQuery() {
    Ext.getCmp("userNameTemp").setValue('');
    orgTree.setValue('');
}

function getList() {
    var params = {};
    params.name = Ext.get('userNameTemp').getValue();
    storeClassManage.baseParams = params;
    storeClassManage.load({
        callback: function (r, options, success) {
            if (success == false) {
                Ext.Msg.alert("错误", storeClassManage.reader.jsonData.msg);
            }
        }
    });
}

Ext.onReady(function () {
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';
    var port = new Ext.Viewport({
        layout: 'fit',
        frame: true,
        items: [this.classManage]
    });
});